package com.hndzyu.yd.customtask;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.hndzyu.yd.R;
import com.hndzyu.yd.bean.UserBean;
import com.hndzyu.yd.url.Path;
import com.hndzyu.yd.utils.OkHttpDownloadJsonUtil;
import com.hndzyu.yd.widget.MyGridView;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PictureUploadActivity extends AppCompatActivity {

    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.et_text)
    EditText etText;
    @BindView(R.id.gridView)
    MyGridView gridView;
    @BindView(R.id.iv_chakan)
    ImageView ivChakan;
    @BindView(R.id.rl)
    RelativeLayout rl;
    private ProgressDialog dialog;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;
    private String uploadpath = ""; //上传到服务器返回图片名
    private int taskid = 0;
    List<String> url = new ArrayList<>();
    private boolean card = false;
    private boolean circle = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_upload);
        ButterKnife.bind(this);
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.colorAccent).init();
        taskid = getIntent().getIntExtra("taskid", 0);
        if ("".equals(getIntent().getStringExtra("examplepic"))) {
            card = true;
        } else if ("0".equals(getIntent().getStringExtra("examplepic"))) {
            circle = true;
            etText.setHint("请输入完成任务的微信号,以便客服审核");
        } else {
            url = Arrays.asList(getIntent().getStringExtra("examplepic").split(","));
            //url = Arrays.asList("/uploads/avatar/20181108/7610d186a77fa444b30a879d002cb46a.png,/uploads/avatar/20181108/7610d186a77fa444b30a879d002cb46a.png,/uploads/avatar/20181108/7610d186a77fa444b30a879d002cb46a.png".split(","));
            maxSelectNum = 9;
        }
        initData();
    }

    private void initData() {
        gridView.setAdapter(new ImageAdapter(PictureUploadActivity.this, url));
        topTitle.setText("参与活动");
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(false);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在加上传...Loading");
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                PictureSelector.create(PictureUploadActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(maxSelectNum - selectList.size())
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(PictureUploadActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(PictureUploadActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(PictureUploadActivity.this).externalPictureAudio(media.getPath());
                            break;
                        default:
                            break;
                    }
                }
            }
        });
    }

    @OnClick({R.id.top_back, R.id.tv_commit, R.id.iv_chakan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.tv_commit:
                if (card) {
                    if (selectList.size() <= 0) {
                        Toast.makeText(this, "请至少上传一张截图", Toast.LENGTH_SHORT).show();
                    } else {
                        dialog.show();
                        upload(etText.getText().toString(), selectList);
                    }
                } else {
                    if ("".equals(etText.getText().toString())) {
                        Toast.makeText(this, "请先填写提交内容", Toast.LENGTH_SHORT).show();
                    } else {
                        if (selectList.size() <= 0) {
                            Toast.makeText(this, "请至少上传一张截图", Toast.LENGTH_SHORT).show();
                        } else {
                            dialog.show();
                            upload(etText.getText().toString(), selectList);
                        }
                    }
                }
                break;
            case R.id.iv_chakan:
                ivChakan.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void upload(final String content, final List<LocalMedia> list) {
        if (list != null) {
            OkHttpClient okHttpClient = new OkHttpClient();
            for (int i = 0; i < list.size(); i++) {
                File file = new File(list.get(i).getPath());
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("pic", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
                RequestBody requestBody = builder.build();
                Request request = new Request.Builder()
                        .url(Path.subMorePic)
                        .post(requestBody)
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG", "onFailure: " + e);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PictureUploadActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        final String str = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if ("".equals(uploadpath)) {
                                    uploadpath = str;
                                } else {
                                    uploadpath = uploadpath + "," + str;
                                }
                                if (Arrays.asList(uploadpath.split(",")).size() == list.size()) {
                                    if (card) {
                                        submitCard();
                                    } else if (circle){
                                        submitCircle();
                                    }else {
                                        submit(content, uploadpath);
                                    }
                                }
                            }
                        });
                    }
                });
            }
        }
    }

    private void submitCard() {
        OkHttpDownloadJsonUtil.downloadJson(PictureUploadActivity.this, Path.CARDPUSH(UserBean.uid, taskid, uploadpath, etText.getText().toString()), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Log.d("TAG", json);
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("info")) {
                            Toast.makeText(PictureUploadActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                        dialog.cancel();
                        if (jsonObject.has("status") && jsonObject.getInt("status") == 1) {
                            setResult(110);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    //发圈截图
    private void submitCircle() {
        OkHttpDownloadJsonUtil.downloadJson(PictureUploadActivity.this, Path.subFq(UserBean.uid, taskid, uploadpath, etText.getText().toString()), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Log.d("TAG", json);
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("info")) {
                            Toast.makeText(PictureUploadActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                        dialog.cancel();
                        if (jsonObject.has("status") && jsonObject.getInt("status") == 1) {

                            setResult(110);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void submit(String content, String imgs) {
        //uid=10033&taskid=1&scontent=填写文字&simg=图片路径
        OkHttpDownloadJsonUtil.downloadJson(PictureUploadActivity.this, Path.subTask + "?uid=" + UserBean.uid + "&taskid=" + taskid +
                "&scontent=" + content + "&simg=" + imgs, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    Log.d("TAG", json);
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("info")) {
                            Toast.makeText(PictureUploadActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                        }
                        if (jsonObject.has("status") && jsonObject.getInt("status") == 1) {
                            dialog.dismiss();
                            dialog.cancel();
                            setResult(110);
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    class ImageAdapter extends BaseAdapter {
        private List<String> datas;
        private Context mContext;

        public ImageAdapter(Context mContext, List<String> datas) {
            this.mContext = mContext;
            this.datas = datas;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int i) {
            return datas.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder vh;
            if (view == null) {
                vh = new ViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.item_source_image, null);
                vh.ivImage = (ImageView) view.findViewById(R.id.iv_img);
                view.setTag(vh);
            } else {
                vh = (ViewHolder) view.getTag();
            }
            Glide.with(mContext).load(Path.BASE_URL + datas.get(i)).into(vh.ivImage);
            vh.ivImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ivChakan.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(Path.BASE_URL + datas.get(i)).into(ivChakan);
                }
            });
            return view;
        }

        class ViewHolder {
            public ImageView ivImage;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
